package com.example.boos.ui.home;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.MainActivity;
import com.example.boos.R;
import com.example.boos.pojo.Food;
import com.example.boos.pojo.FoodType;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.ShowPopuWIndow;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

/**
 * Created by Vin on 08/12/2016.
 */

public class RightAdapter extends BaseAdapter implements StickyListHeadersAdapter {

    private Activity mContext;
   // private RightAdapterCallback mCallback;
    private List<Food> mData;

    private LayoutInflater mInflater;

    public static int position = 0;
    // 更新图片
    public void update(String url){
        mData.get(position).setFoodImage(url);
        update(position,mData.get(position));
    }


    public RightAdapter(Activity mContext, List<Food> mData) {
        this.mContext = mContext;
        this.mData = mData;
        //this.mCallback = callback;
        mInflater = LayoutInflater.from(mContext);
    }

    //更新
    public void update(int position,Food model){
        mData.set(position,model);
        notifyDataSetChanged();
    }

    public void updateAll(List<Food>data){
        mData = data;
        notifyDataSetChanged();
    }

    // 填充标签名
    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder holder;
        if (null == convertView) {
            convertView = mInflater.inflate(R.layout.right_header,null);
            holder = new HeaderViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (HeaderViewHolder) convertView.getTag();
        }

        holder.title.setText(mData.get(position).getFoodTypeName());
        return convertView;
    }

    // 获取到 菜单类型的id
    @Override
    public long getHeaderId(int position) {
        return mData.get(position).getFoodTypeId();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int i) {
        return mData.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    // 填充数据 菜品
    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

        ViewHolder holder;
        if (null == view) {
            // right_item  菜品项
            view = mInflater.inflate(R.layout.right_item,null);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }

        // 填充数据
        final Food sm = mData.get(i);
        holder.name.setText(sm.getFoodName());
        /*String.format(holder.price.getText().toString(),*/
        holder.price.setText(String.valueOf(sm.getFoodPrice()));
        Glide.with(MainActivity.getMainActivity()).load(mData.get(i).getFoodImage()).
                /*skipMemoryCache(true).
                signature(new ObjectKey(System.currentTimeMillis())).
                diskCacheStrategy(DiskCacheStrategy.NONE).*/
                into(holder.mRightFoodImage);

        // 监听器
        holder.mRightFoodImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 上传图片
                position = i;
                ShowPopuWIndow.showPopueWindow(MainActivity.getMainActivity(),1);
            }
        });

        // 删除菜品
        holder.remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(v.getContext())
                        .setTitle("确认删除该菜品？")
                        .setMessage("确定吗")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int hich) {
                                // 发送删除请求
                                Integer foodId = mData.get(i).getId();
                                Food food = new Food();
                                food.setId(foodId);
                                food.setFoodStatus(0);
                                MyThreadPool.doJob(new Runnable() {
                                    @Override
                                    public void run() {
                                        Boolean isDel = (Boolean) MyPost.doPost("delFood",food);
                                        Message msg = new Message();
                                        msg.what = 3;
                                        if(isDel){
                                            // 如果删除成功
                                            mData.remove(i);
                                        }
                                        msg.obj = isDel;
                                        MainActivity.handler.sendMessage(msg);
                                    }
                                });
                                // 隐藏对话框
                                dialog.cancel();

                            }
                        })
                        .setNegativeButton("否", null)
                        .show();

            }
        });

        // 更新菜品
        holder.update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUpdateFood(mContext,i);
            }
        });

        return view;
    }


    // 菜品
    class ViewHolder {
        TextView name;
        TextView price;
        ImageView update;
        ImageView remove;
        ImageView mRightFoodImage;

        public ViewHolder(View view) {
            name = (TextView) view.findViewById(R.id.name);
            price = (TextView) view.findViewById(R.id.price);
            update =  view.findViewById(R.id.update);
            remove =  view.findViewById(R.id.remove);
            mRightFoodImage = (ImageView) view.findViewById(R.id.rightFoodImage);
        }
    }

    //标题
    class HeaderViewHolder {
        TextView title;
        public HeaderViewHolder(View view) {
            title = (TextView) view.findViewById(R.id.header_title);
        }
    }

    private void CloneFood(Food sourceFood,Food food){
        food.setId(sourceFood.getId());
        food.setFoodStock(sourceFood.getFoodStock());
        food.setFoodTypeId(sourceFood.getFoodTypeId());
        food.setFoodPrice(sourceFood.getFoodPrice());
        food.setFoodInfo(sourceFood.getFoodInfo());
        food.setFoodName(sourceFood.getFoodName());
        food.setFoodStatus(sourceFood.getFoodStatus());
        food.setAddNums(sourceFood.getAddNums());
        food.setFoodImage(sourceFood.getFoodImage());
        food.setFoodTypeName(sourceFood.getFoodTypeName());
        food.setStoreId(sourceFood.getStoreId());
    }

    // 显示更新菜品窗口
    private void showUpdateFood(Activity act,int i){
            Food food = mData.get(i);
            Food cloneFood = new Food();
            CloneFood(food,cloneFood);
            View popView = View.inflate(act,R.layout.update_food,null);
            Button bt_update = (Button) popView.findViewById(R.id.updateFood);
            Button bt_cancle = (Button) popView.findViewById(R.id.cancelUpdateFood);
            EditText foodName = (EditText) popView.findViewById(R.id.updateFoodName);
            EditText foodPrice = popView.findViewById(R.id.updateFoodPrice);
            EditText foodInfo = popView.findViewById(R.id.updateFoodInfo);
        Spinner updateFoodType = popView.findViewById(R.id.updateFoodType);
        Spinner updateFoodStock = popView.findViewById(R.id.updateFoodStock);

            // 设置数据
            foodName.setText(food.getFoodName());
            foodPrice.setText(String.valueOf(food.getFoodPrice()));
            foodInfo.setText(food.getFoodInfo());
            // 为菜品类型选择设置数据
            List<String> foodTypeName = new ArrayList<>();
            int typePosition  = 0;
            int ii = 0;
            for(FoodType y : HomeFragment.leftData){
                foodTypeName.add(y.getFoodTypeName());
                if(y.getId() == food.getFoodTypeId()){
                    typePosition = ii;
                }
                ii++;
            }
            // 适配器
        ArrayAdapter<String> adapterType = new ArrayAdapter<>(act, R.layout.spinner_item,foodTypeName);
            ArrayAdapter<String> adapterStock = new ArrayAdapter<>(act,R.layout.spinner_item,new String[]{"库存空","有库存"});
            // 设置适配器
        updateFoodType.setAdapter(adapterType);
        updateFoodStock.setAdapter(adapterStock);
        // 选择选项
        updateFoodType.setSelection(typePosition);
        updateFoodStock.setSelection(food.getFoodStock());


            //获取屏幕宽高
            int weight = act.getResources().getDisplayMetrics().widthPixels;
            int height = act.getResources().getDisplayMetrics().heightPixels;

            final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
            // popupWindow.setAnimationStyle(R.style.anim_popup_dir);
            popupWindow.setFocusable(true);
            //点击外部popueWindow消失
            popupWindow.setOutsideTouchable(true);

        // 确认修改监听器
        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取数据
                food.setFoodName(foodName.getText().toString());
                food.setFoodInfo(foodInfo.getText().toString());
                food.setFoodPrice(Float.parseFloat(foodPrice.getText().toString()));
                // 状态 类型 进行改变
                int foodTypePosition = updateFoodType.getSelectedItemPosition();
                int stock = updateFoodStock.getSelectedItemPosition();
                food.setFoodTypeId(HomeFragment.leftData.get(foodTypePosition).getId());
                // typeName 也要改一下呀
                food.setFoodTypeName(HomeFragment.leftData.get(foodTypePosition).getFoodTypeName());
                food.setFoodStock(stock);
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Boolean isUpdate = (Boolean) MyPost.doPost("updateFood",food);
                        Message msg = new Message();
                        msg.what = 4;
                        msg.obj = isUpdate;
                        if(!isUpdate){
                            // 更新失败
                            CloneFood(cloneFood,food);
                        }else{
                            if(food.getFoodTypeId() != cloneFood.getFoodTypeId()){
                                // 排下序
                                HomeFragment.rightData.sort(new Comparator<Food>() {
                                    @Override
                                    public int compare(Food o1, Food o2) {
                                        return o1.getFoodTypeId()-o2.getFoodTypeId();
                                    }
                                });
                            }
                        }
                        MainActivity.handler.sendMessage(msg);
                    }
                });
                popupWindow.dismiss();
            }
        });




            bt_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss(); // 隐藏popupWindow

                }
            });

            //popupWindow消失屏幕变为不透明
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = act.getWindow().getAttributes();
                    lp.alpha = 1.0f;
                    act.getWindow().setAttributes(lp);
                }
            });
            //popupWindow出现屏幕变为半透明
            WindowManager.LayoutParams lp = act.getWindow().getAttributes();
            lp.alpha = 0.5f;
            act.getWindow().setAttributes(lp);
            popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
        }

}
